﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace _1._2._2_基于TcpListener的_Web_服务器
{
    public class SimpleTcpListener
    {
        public void Run()
        {
            //操作和socket的方式差不多，socket可以异步
            //但是有一个问题，TcpListener方式打开多个有问题，
            //估计是Tcpclient不能异步的原因
            IPAddress address = IPAddress.Loopback;
            int port = 2451;
            IPEndPoint localEP = new IPEndPoint(address, port);
            TcpListener listener = new TcpListener(localEP);
            listener.Start(10);
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                NetworkStream ns= client.GetStream();
                Encoding utf8=Encoding.UTF8;
                byte[] requestBytes=new byte[4096];
                int len=ns.Read(requestBytes,0,4096);
                string requeststring=utf8.GetString(requestBytes,0,len);
                Console.WriteLine(requeststring);

                string statusLines = "HTTP/1.1 200 OK\r\n";
                // 显示请求的内容
                Console.WriteLine(requeststring);
                byte[] statusLinesBytes = utf8.GetBytes(statusLines);
                string responseBody
                    = @"<html>
                            <head><title>来自Socket服务器</title></head>
                            <body><h1>你猜中了么</h1></body>
                        </html>";
                byte[] responseBodyBytes = utf8.GetBytes(responseBody);
                string responseHeader = string.Format(
                    "Content-Type: text/html; charset=UTF-8\r\nContent-Length: {0}\r\n",
                    responseBody.Length
                    );
                byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);


                ns.Write(statusLinesBytes,0,statusLinesBytes.Length);
                ns.Write(responseHeaderBytes,0,responseHeaderBytes.Length);
                ns.Write(new byte[] { 13, 10 },0,2);//不可少
                ns.Write(responseBodyBytes,0,responseBodyBytes.Length);

                client.Close();
                 if (Console.KeyAvailable)
                    break;
            }
            listener.Stop();

        }
    }
}
